package crud

import (
	"os"
	"strings"

	"api/system/helper"
)

var cTempl = `<?php
namespace {{.__NAMESPACE__}};

use app\controller\api\Base;
use app\service\api\{{.__FACADE__}} as DefFacade;

class {{.__CLASS__}} extends Base
{
	public $noNeedLogin = [
    ];
	
    // add 添加数据
    public function add()
    {
        $name = $this->request->param('name', '');

        $flag = DefFacade::doSave([
            'name' => $name,
            'status' => 1,
        ]);
        if (!$flag) {
            return $this->error(DefFacade::getError());
        }

        return $this->success("添加成功");
    }
	
	// edit 编辑数据
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        $name = $this->request->param('name', '');

        $flag = DefFacade::doSave([
            'id' => $id,
            'name' => $name
        ]);
        if (!$flag) {
            return $this->error(DefFacade::getError());
        }

        return $this->success("保存成功");
    }
	
	// info 获取数据信息
    public function info() {
        $id = $this->request->param('id', 0, 'intval');
        $info = DefFacade::info($id);

        return $this->success("获取成功", $info);
    }
	
	// delete 删除数据
    public function delete() {
        $id = $this->request->param('id', 0, 'intval');
        $flag = DefFacade::delete($id);
        if (!$flag) {
            return $this->error(DefFacade::getError());
        }

        return $this->success("删除成功");
    }
	
	// defaults 设置默认值
    public function defaults() {
        $id = $this->request->param('id', 0, 'intval');
        $flag = DefFacade::defaults($id);
        if (!$flag) {
            return $this->error(DefFacade::getError());
        }

        return $this->success("成功设为默认选项");
    }
	
	// list 获取数据列表
    public function list() {
        $page = $this->request->param('page', 0, 'intval');
        $page_size = $this->request->param('page_size', 10, 'intval');

        $data = DefFacade::list([
            'page' => $page,
            'page_size' => $page_size,
        ]);

        return $this->success("获取成功", $data);
    }
}`

// 生成控制器
func (g *cGlobal) MakeController() error {
	inx := strings.LastIndex(g.ControllerPath, "\\")
	nName := g.ControllerPath[:inx]
	err := os.MkdirAll(nName, os.ModePerm)
	if err != nil {
		return err
	}

	facade := ""
	className := ""
	cinx := strings.LastIndex(g.TableName, "_")
	if cinx > 0 {
		facade = helper.LcWords(g.TableName, "_")
		facade = strings.ReplaceAll(facade, "_", "\\")
		lowerClassName := g.TableName[cinx+1:]
		className = helper.UcFirst(lowerClassName)
	} else {
		facade = helper.UcFirst(g.TableName)
		className = helper.UcFirst(g.TableName)
	}

	m := map[string]string{
		"__NAMESPACE__": g.ControllerNameSpace,
		"__FACADE__":    facade + "Facade",
		"__CLASS__":     className,
	}

	fileName := g.ControllerPath
	err = TemplateExec(fileName, cTempl, m)
	if err != nil {
		return err
	}

	return nil
}
